//
//  RAPEmoticonPresentationCell.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/7/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

/// 表情按钮点击通知名称
let RAPEmoticonPresentationCellEmoticonButtonClickedNotification = "RAPEmoticonPresentationCellEmoticonButtonClickedNotification"
/// 删除按钮点击通知名称
let RAPEmoticonPresentationCellDeleteButtonClickedNotification = "RAPEmoticonPresentationCellDeleteButtonClickedNotification"

/// 从info中获取RAPEmoticonModel的key
let RAPEmoticonModelKey = "RAPEmoticonModelKey"


// 一页展示21个按钮（20个表情，一个删除按钮）
// 列数
private let kColNumber: CGFloat = 7
// 行数
private let kRowNumber: CGFloat = 3

protocol RAPEmoticonPresentationCellDelegate: NSObjectProtocol {
    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, emoticonButtonClicked: RAPEmoticonButton)

    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, longPressBegan: UILongPressGestureRecognizer)
    
    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, longPressEnded: UILongPressGestureRecognizer)
}


class RAPEmoticonPresentationCell: UICollectionViewCell {
    
    // MARK: - 自定义属性
    
    private var preButton: RAPEmoticonButton?
    
    /// 代理属性
    weak var delegate: RAPEmoticonPresentationCellDelegate?
    
    var indexPath: NSIndexPath? {
        didSet {
            if indexPath?.section == 0 {
                tipLabel.hidden = false
            } else {
                tipLabel.hidden = true
            }
        }
    }

    var emoticonsForCell: [RAPEmoticonModel]? {
        didSet {
            /*
            清空前20个，再设置title 或 image
            */
            for idx in 0..<Int(kColNumber * kRowNumber - 1) {
                buttonArray[idx].setTitle(nil, forState: UIControlState.Normal)
                buttonArray[idx].setImage(nil, forState: UIControlState.Normal)
            }
            
            // 赋予模型
            for (idx, _) in emoticonsForCell!.enumerate() {
                
                // 赋予模型
                buttonArray[idx].emoticonModel = emoticonsForCell![idx]
            }
        }
    }
    
    private var buttonArray: [RAPEmoticonButton]!
    
    // MARK: - 系统方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        getReady()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func getReady() {
        //
        
        contentView.addGestureRecognizer(longPressGR)
        
        contentView.addSubview(emoticonGridView)
        contentView.addSubview(tipLabel)
        
        installConstraints()
    }
    
    private func installConstraints() {
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-10)
        }
        emoticonGridView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let btnW = (self.frame.width - 10) / kColNumber // 计算宽度
        let btnH = (self.frame.height - 20) / kRowNumber // 计算高度
        
        // 排布表情button
        for (idx, btn) in emoticonGridView.subviews.enumerate() {
            let colIdx = CGFloat(idx % Int(kColNumber))
            let rowIdx = CGFloat(idx / Int(kColNumber))
            
            btn.frame = CGRectMake(colIdx * btnW + 5, rowIdx * btnH, btnW, btnH)
        }
    }
    
    @objc private func emoticonButtonClicked(sender: RAPEmoticonButton) {
        
        // TODO: 本行代码可以优化掉
        delegate?.emoticonPresentationCell(self, emoticonButtonClicked: sender)
        
        /*
        发送删除按钮的通知
        */
        guard let opEmoticonModel = sender.emoticonModel else {
            NSNotificationCenter.defaultCenter().postNotificationName(RAPEmoticonPresentationCellDeleteButtonClickedNotification, object: self)
            return
        }
        
        /*
        发送通知，将表情点击事件回传给控制器
        */
        NSNotificationCenter.defaultCenter().postNotificationName(RAPEmoticonPresentationCellEmoticonButtonClickedNotification, object: self, userInfo: [RAPEmoticonModelKey : opEmoticonModel])
        
        // 将表情添加至最近数组
        RAPEmoticonKeyboardViewModel.sharedViewModel.addRecentEmoticon(opEmoticonModel)

    }
    
    // MARK: - 动作方法
    @objc private func longPress(longPressGR: UILongPressGestureRecognizer) {
        
        ///  从buttonArray中找出point所在的按钮
        ///
        ///  - parameter point: 长按所在的点
        ///
        ///  - returns: 所在的按钮
        func emoticonButtonContainsPoint(point: CGPoint) -> RAPEmoticonButton? {
            /*
            遍历表情按钮数组
            */
            
            for btn in buttonArray {
                if CGRectContainsPoint(btn.frame, point) {
                    return btn
                }
            }
            return nil
        }
        
        //===============分割线===============
        
        
        
        let point = longPressGR.locationInView(contentView)
        
        switch longPressGR.state {
        case .Began:
            RAPLog("began")
            // 放大镜显示
            delegate?.emoticonPresentationCell(self, longPressBegan: longPressGR)
        case .Changed:
            // 放大镜显示
            delegate?.emoticonPresentationCell(self, longPressBegan: longPressGR)
            guard let opEmoticonButton = emoticonButtonContainsPoint(point) else {
                // 让放大镜消失
                delegate?.emoticonPresentationCell(self, longPressEnded: longPressGR)
                return
            }
            // TODO: 本段代码需要整理
            /*
            如果模型为空，放大镜也消失
            */
            if opEmoticonButton.emoticonModel == nil {
                // 让放大镜消失
                delegate?.emoticonPresentationCell(self, longPressEnded: longPressGR)
                return
            }
            
            if opEmoticonButton === preButton {
                return
            }
            preButton = opEmoticonButton
            
            delegate?.emoticonPresentationCell(self, emoticonButtonClicked: opEmoticonButton)
            RAPLog("changed")
            // 放大镜改变位置
        case .Ended:
            RAPLog("ended")
            // 放大镜消失
            delegate?.emoticonPresentationCell(self, longPressEnded: longPressGR)
        default:
            return
        }
        
    }
    
    // MARK: - 懒加载
    
    lazy var longPressGR: UILongPressGestureRecognizer = {
        let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPress:")
        longPressGR.minimumPressDuration = 0.25
        return longPressGR
    }()
    
    private lazy var emoticonGridView: UIView = {
        let emoticonGridView = UIView()

        for i in 0..<21 {
            let btn = RAPEmoticonButton()
            btn.addTarget(self, action: "emoticonButtonClicked:", forControlEvents: UIControlEvents.TouchDown)
            btn.titleLabel?.font = UIFont.systemFontOfSize(36)
            btn.adjustsImageWhenHighlighted = false
            if i == 20 { // 将最后一个按钮设置为删除图片
                btn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
            emoticonGridView.addSubview(btn)
        }
        self.buttonArray = emoticonGridView.subviews as! [RAPEmoticonButton]
        
        return emoticonGridView
    }()
    
    /// 提示标签
    private lazy var tipLabel: UILabel = UILabel(text: "最近使用的表情^_^", fontSize: 12)
    

}
